package com.gqh.weather.util;

import java.security.MessageDigest;
import java.util.Base64;

/**
 * 密码加密工具类
 * 对应Go系统的authcode功能
 */
public class PasswordUtil {
    
    private static final String SALT = "education_system_2024";
    
    /**
     * 加密密码
     * 
     * @param password 原始密码
     * @return 加密后的密码
     */
    public static String encode(String password) {
        if (password == null || password.trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }
        
        try {
            // 添加盐值
            String saltedPassword = password + SALT;
            
            // MD5加密
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(saltedPassword.getBytes("UTF-8"));
            
            // Base64编码
            return Base64.getEncoder().encodeToString(hashBytes);
        } catch (Exception e) {
            throw new RuntimeException("密码加密失败", e);
        }
    }
    
    /**
     * 验证密码
     * 
     * @param rawPassword 原始密码
     * @param encodedPassword 加密后的密码
     * @return 是否匹配
     */
    public static boolean matches(String rawPassword, String encodedPassword) {
        if (rawPassword == null || encodedPassword == null) {
            return false;
        }
        
        try {
            String encoded = encode(rawPassword);
            return encoded.equals(encodedPassword);
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 生成随机密码
     * 
     * @param length 密码长度
     * @return 随机密码
     */
    public static String generateRandomPassword(int length) {
        if (length < 6 || length > 12) {
            throw new IllegalArgumentException("密码长度必须在6-12位之间");
        }
        
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder password = new StringBuilder();
        
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * chars.length());
            password.append(chars.charAt(index));
        }
        
        return password.toString();
    }

    public static void main(String[] args) {
        System.out.println(PasswordUtil.encode("88886666"));
    }
}